package com.milkway.database;

import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

public class DbUtils {
  public static <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) {
    T result = null;
    DataSource ds = getDataSource();
    if (ds != null) {
      QueryRunner run = new QueryRunner(ds);
      try {
        result = run.query(sql, rsh, params);
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    return result;
  }

  public static DataSource getDataSource() {
    DataSource ds = null;
    InitialContext cxt = null;

    try {
      cxt = new InitialContext();
      if (cxt != null) {
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/milkway");
      }
    } catch (NamingException e) {
      e.printStackTrace();
    }

    return ds;
  }
}
